'use strict';

const Service = require('egg').Service;
class CategoryService extends Service {
  constructor(ctx) {
    super(ctx);
    this.user = {};
  }

  async create(params) {
    const { mysql } = this.app;
    try {
      const { categoryTag, categoryName } = params;
      const createTime = new Date();
      const updateTime = new Date();
      const result = await mysql.query('INSERT INTO cms_category(category_tag, category_name, created_at, updated_at) VALUES (?, ?, ?, ?);', [ categoryTag, categoryName, createTime, updateTime ]);
      if (result.affectedRows === 1) {
        return result.insertId;
      }
    } catch (error) {
      this.ctx.throw(500, error.message);
    }
  }

  async find(params) {
    const { mysql } = this.app;
    const { helper: { pagination } } = this.ctx;
    try {
      const { categoryName, categoryTag, page, size } = params;
      const pagger = pagination(page, size);
      const filters = {
        category_name: { REGEXP: categoryName },
        category_tag: { '=': categoryTag },
      };
      const segments = [];
      const values = [];
      Object.keys(filters).forEach(key => {
        const item = filters[key];
        const k = Object.keys(item)[0];
        if (item[k]) {
          segments.push(`(${key} ${k} ? )`);
          values.push(item[k]);
        }
      });

      const select = 'SELECT * FROM `cms_category`';
      const wheres = segments.length ? `WHERE ${segments.join(' OR ')}` : '';
      const order = 'ORDER BY `created_at` ASC';
      const limit = 'LIMIT ? OFFSET ?';

      const count = await mysql.query('SELECT COUNT(*) as total FROM `cms_category`' + wheres, [ ...values ]);
      const result = await mysql.query([ select, wheres, order, limit ].join(' '), [ ...values, pagger.limit, pagger.offset ]);

      return {
        pagination: {
          total: count[0].total,
          page: pagger.page,
          size: pagger.size,
        },
        list: result,
      };
    } catch (error) {
      this.ctx.throw(500);
    }
  }

  async findOne(params) {
    const { mysql } = this.app;
    try {
      const { id } = params;
      const result = await mysql.get('cms_category', { id });
      return result;
    } catch (error) {
      this.ctx.throw(500, error.message);
    }
  }

  async update(params) {
    const { mysql } = this.app;
    try {
      const { id, categoryTag, categoryName } = params;
      const updateTime = new Date();
      const result = await mysql.query('UPDATE `cms_category` SET `category_tag`=?, `category_name`=?, `updated_at`=? WHERE `category_id`=?', [ categoryTag, categoryName, updateTime, id ]);
      if (result.affectedRows === 1) {
        return {};
      }
    } catch (error) {
      this.ctx.throw(500, error.message);
    }
  }

  async destroy(params) {
    const { mysql } = this.app;
    try {
      const { id } = params;
      const result = await mysql.delete('cms_category', { category_id: id });
      if (result.affectedRows === 1) {
        return {};
      }
    } catch (error) {
      this.ctx.throw(500, error.message);
    }
  }
}

module.exports = CategoryService;
